//
//  GetHTMLSource.m
//  KotnetAutologin
//
//	get the html source of a website
//
//  Created by Kristof Marien on 4/01/10.
//  Copyright 2010 KotnetAutologin. All rights reserved.
//

#import "GetHTMLSource.h"


@implementation GetHTMLSource

@synthesize url;
@synthesize data;
@synthesize delegate;
@synthesize receivedCallback;
@synthesize errorCallback;

/**
 *  release variables
 */
- (void)terminate 
{
	[theConnection cancel];
	[theConnection release];
	[receivedData release];
	[url release];
	[delegate release];
}
/**
 *  start loading source
 */
- (void) getSource:(id)requestDelegate receivedSelector:(SEL)receivedSelector errorSelector:(SEL)errorSelector
{
	self.delegate = requestDelegate;
	self.receivedCallback = receivedSelector;
	self.errorCallback = errorSelector;
	
	if (self.url == @"") {
		NSLog(@"Error - Please enter a URL.");
		return;
	}
	theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
	[theRequest setTimeoutInterval:10];
	[theRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	if (self.data) {
		[theRequest setHTTPMethod:@"POST"];
		[theRequest setHTTPBody:[NSData dataWithBytes:[self.data UTF8String] length:[self.data length]]];
	}
	theConnection = [NSURLConnection alloc];
	[theConnection initWithRequest:theRequest delegate:self];
	if (theConnection) {
		receivedData = [NSMutableData alloc];
	} else {
		if (self.delegate && self.errorCallback) {
			if ([self.delegate respondsToSelector:self.errorCallback]) {
				[self.delegate performSelector:self.errorCallback];
			}
		}
	}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataSource
{
    [receivedData appendData:dataSource];
}
/**
 *  error while loading source
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	if (self.delegate && self.errorCallback) {
		if ([self.delegate respondsToSelector:self.errorCallback]) {
			[self.delegate performSelector:self.errorCallback];
		}
	}
	[self terminate];
}
/**
 *  source loaded
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	if (self.delegate && self.receivedCallback) {
		if ([self.delegate respondsToSelector:self.receivedCallback]) {
			NSString *source = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
			[self.delegate performSelector:self.receivedCallback withObject:source];
			[source release];
		}
	}
	[self terminate];
}
@end
